package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.*;
import com.sky.utils.JwtUtil;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单
 */
@Service
@Slf4j
public class OrderServiceImpl
        extends ServiceImpl<OrderMapper, Orders>
        implements OrderService {

    @Autowired
    HttpServletRequest request;
    @Autowired
    UserService userService;
    @Autowired
    AddressBookService addressBookService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    private UserMapper  userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO dto) {
        /////////////////////// 1. 基础数据准备：用户信息、地址信息、购物车列表
        //用户信息
        String authentication = request.getHeader("authentication");
        Long userId = JwtUtil.parseJWT(authentication).get("userId", Long.class);
        User user = userService.getById(userId);
        //地址信息
        Long addressBookId = dto.getAddressBookId();
        AddressBook address = addressBookService.getById(addressBookId);
        //购物车列表
        List<ShoppingCart> carts = shoppingCartService.query().eq("user_id", userId).list();


        /////////////////////// 2. 构建订单对象 Orders
        Orders orders = Orders.builder()
                .number(String.valueOf(System.currentTimeMillis()))
                .status(1)
                .userId(userId)
                .addressBookId(addressBookId)
                .orderTime(LocalDateTime.now())
                .payMethod(dto.getPayMethod())
                .payStatus(0)
                .amount(dto.getAmount())
                .remark(dto.getRemark())
                .userName(user.getName())
                .phone(address.getPhone())
                .address(address.getDetail())
                .consignee(address.getConsignee())
                .estimatedDeliveryTime(dto.getEstimatedDeliveryTime())
                .deliveryStatus(dto.getDeliveryStatus())
                .packAmount(dto.getPackAmount())
                .tablewareNumber(dto.getTablewareNumber())
                .tablewareStatus(dto.getTablewareStatus())
                .build();

        this.save(orders);


        /////////////////////// 3. 构建订单项列表 List<OrderDetail>
        carts.forEach(cart -> {
            OrderDetail orderDetail = OrderDetail.builder()
                    .name(cart.getName())
                    .orderId(orders.getId())
                    .dishId(cart.getDishId())
                    .setmealId(cart.getSetmealId())
                    .dishFlavor(cart.getDishFlavor())
                    .number(cart.getNumber())
                    .amount(cart.getAmount())
                    .image(cart.getImage())
                    .build();

            orderDetailService.save(orderDetail);
        });

        /////////////////////// 4. 删除购物车数据
        shoppingCartService.update().eq("user_id", userId).remove();

        /////////////////////// 5. 构建OrderSubmitVO对象返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }


    /**
     * 获取订单概览信息
     *
     * 此方法从各个状态中汇总订单数量，包括所有订单、已取消订单、已完成订单、已发货订单和待处理订单
     * 它通过调用orderMapper的不同方法来获取各种状态的订单数量，并将这些数据封装到OrderOverViewVO对象中返回
     * 这样做可以提供一个集中的地方来获取订单的全局视图，便于监控和管理
     *
     * @return OrderOverViewVO对象，包含各种状态的订单数量
     */
    public OrderOverViewVO getOverviewOrders() {
        // 获取当前日期
        LocalDate now = LocalDate.now();
        // 构造当天开始时间
        LocalDateTime begin = LocalDateTime.of(now, LocalTime.MIN);
        // 构造当天结束时间
        LocalDateTime end = LocalDateTime.of(now, LocalTime.MAX);

        // 创建一个HashMap用于存储查询参数
        Map<String, Object> map = new HashMap<>();
        // 将当天的开始和结束时间放入查询参数中
        map.put("begin", begin);
        map.put("end", end);
        // 查询当天的所有订单数量
        Integer allOrders = orderMapper.orderByMap(map);
        // 更新查询参数，添加订单状态为已取消
        map.put("status", Orders.CANCELLED);
        // 查询当天的已取消订单数量
        Integer cancelledOrders = orderMapper.orderByMap(map);
        // 更新查询参数，添加订单状态为已完成
        map.put("status", Orders.COMPLETED);
        // 查询当天的已完成订单数量
        Integer completedOrders = orderMapper.orderByMap(map);
        // 更新查询参数，添加订单状态为已确认
        map.put("status", Orders.CONFIRMED);
        // 查询当天的已确认订单数量
        Integer deliveredOrders = orderMapper.orderByMap(map);
        // 更新查询参数，添加订单状态为待确认
        map.put("status", Orders.TO_BE_CONFIRMED);
        // 查询当天的待确认订单数量
        Integer waitingOrders = orderMapper.orderByMap(map);

        // 使用构建者模式创建并返回OrderOverViewVO对象，封装各种状态的订单数量
        return OrderOverViewVO.builder()
                .allOrders(allOrders)
                .cancelledOrders(cancelledOrders)
                .completedOrders(completedOrders)
                .deliveredOrders(deliveredOrders)
                .waitingOrders(waitingOrders)
                .build();
    }


    /**
     * 获取业务数据概述
     *
     * 本方法用于统计特定时间范围内的业务数据，包括新用户数、总订单数、有效订单数、营业额、单价和订单完成率
     * 时间范围为当前日期的开始到结束，即从00:00:00到23:59:59
     *
     * @return BusinessDataVO 包含业务数据概述的对象
     */
    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {

        // 创建一个映射来存储查询条件
        Map<String, Object> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);

        // 统计新用户数
        Integer newUsers = userMapper.countByMap(map);
        newUsers = newUsers == null ? 0 : newUsers;

        // 统计总订单数
        Integer totalOrderCount = orderMapper.orderByMap(map);
        totalOrderCount = totalOrderCount == null ? 0 : totalOrderCount;

        // 添加订单状态为已完成的条件，以统计有效订单数
        map.put("status", Orders.COMPLETED);
        Integer validOrderCount = orderMapper.orderByMap(map);
        validOrderCount = validOrderCount == null ? 0 : validOrderCount;

        // 将有效订单数转换为Double类型，以便进行除法运算
        Double validOrder = validOrderCount.doubleValue();

        // 统计营业额
        Double turnover = orderMapper.sumByMap(map);
        turnover = turnover == null ? 0 : turnover;

        // 计算单价
        Double unitPrice = turnover / validOrderCount;
        //unitPrice=unitPrice==null?0:unitPrice;

        // 计算订单完成率
        Double orderCompletionRate = validOrder / totalOrderCount;
        //orderCompletionRate=orderCompletionRate==null?0:orderCompletionRate;

        // 构建并返回业务数据概述对象
        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .newUsers(newUsers)
                .unitPrice(unitPrice)
                .build();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map map = new HashMap();
        map.put("orderId", ordersDB.getId());
        map.put("type", 1);
        map.put("content","订单号"+outTradeNo);

        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }


}